﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace Wage
{
    public class WageCalculation
    {

        public static WageCalculatioResult Calculation(IEnumerable<SalaryItem> salaryItems)
        {
            WageCalculatioResult res = new WageCalculatioResult();
            //获取所有的组名字
            res.TotalItems = new List<SalaryItem>();

            var t1 = new Task(() =>
            {
                IEnumerable<SalaryItem> Items = salaryItems.Distinct(new SalaryNameComparer());
                foreach (var item in Items)
                {
                    res.TotalItems.Add(new SalaryItem { Name = item.Name });
                }
                //res.TotalItems.Add(new SalaryItem { Name = "总计" });
            });
            t1.Start();

            //获取所有的月份
            List<DateTime> totalTimes = new List<DateTime>();
            var t2 = new Task(() =>
            {

                IEnumerable<SalaryItem> Items = salaryItems.Distinct(new SalaryTimeComparer());
                foreach (var item in Items)
                {
                    totalTimes.Add(item.Time);
                }

            });
            t2.Start();
            Task.WaitAll(t1, t2);

            //按月份分组，计算当月的总数
            List<Task> tasks = new List<Task>();
            res.SalaryByMonth = new List<SalaryMonth>();
            foreach (var time in totalTimes)
            {
                var t = new Task(() =>
                {
                    var monthDate = salaryItems.Where(s => s.Time == time);
                    SalaryMonth salaryMonth = new SalaryMonth();
                    salaryMonth.Time = time;
                    decimal monthSum = 0;
                    //此处需要按照名字去循环
                    for (int i = 0; i < res.TotalItems.Count; i++)
                    {
                        // SalaryItem item = res.TotalItems[i];
                        var searchRes = monthDate.SingleOrDefault(s => s.Name == res.TotalItems[i].Name);
                        searchRes.Name = res.TotalItems[i].Name;//如果为默认，就起个名字
                        monthSum += searchRes.Amount;//计算月总数
                        salaryMonth.TotalItems.Add(searchRes);
                        res.TotalItems[i].Amount += searchRes.Amount;//计算项总数


                    }
                    salaryMonth.Total = monthSum;
                    res.SalaryByMonth.Add(salaryMonth);

                });
                tasks.Add(t);
                t.Start();

            }
            Task.WaitAll(tasks.ToArray());
            //计算 整个的 总数

            res.Total = res.TotalItems.Sum(s => s.Amount);




            return res;
        }
    }

}
